<template>
    <div class="chat" ref="chatContent">
        <v-navbar></v-navbar>
        <div class="chat-wrapper">
            <ul>
                <li v-for="(v, i) in nwes" :key="i" class="item">
                    <div v-if="show(i)" class="time">{{v.ctime | formatDate }}</div>
                    <div class="wrapper" :class="{'right': v.userId === 0}">
                        <img class="img" :src="v.user" width="40" height="40" alt="">
                        <div class="jiao"></div>
                        <p class="text">{{v.content}}</p>
                    </div>
                </li>
            </ul>
        </div>
        <div class="input">
            <input type="text" v-model="content" ref="input">
            <button class="send" @click="doSend">发送</button>
        </div>
    </div>
</template>

<script>
import navbar from '@c/navbar/navbar'
import user from '@imgs/chat/user.png'
import { mapState, mapMutations } from 'vuex'
import { formatDate } from './formatDate.js'
import { vpost, sonpost, fpost, gpost, vlink } from '@api/axios'
import { tokenPost, jtpost, gtpost, tokenLink, jtget } from '@api/axiosByToken'
import { Connect } from '@api/apiUrl'
// const time1 = new Date

export default {
	name: 'chat',
	data() {
		return {
			user: user,
			content: '',
			// 模拟数据
			nwes: [],
			sock: {},
			stomp: null,
			selfIcon: '', //个人头像
			friendIcon: '', //好友头像
		}
	},
	components: {
		'v-navbar': navbar,
	},
	computed: {
		...mapState(['wtitle', 'rback', 'msgList']),
	},
	methods: {
		...mapMutations(['WTITLE', 'RBACK']),
		// 获取聊天记录
		getChatHis() {
			let getData = {
				userId: localStorage.getItem('userId'),
				friendId: this.$route.params.friendId,
			}
			tokenPost(tokenLink.mate.selectChatHis, getData).then(re => {
				console.log(re)
				if (re.status == 0) {
					this.outgivingChaHis(re)
				}
			})
		},
		// 分发聊天记录
		outgivingChaHis(re) {
			let hisArr = re.data
			console.log(re.data)
			for (let i = 0; i < hisArr.length; i++) {
				let hisobj = {}
				let currenID = localStorage.getItem('userId')

				// 判断ID
				currenID != hisArr[i].sendUserId
					? (hisobj.userId = 1)
					: (hisobj.userId = 0)
				hisobj.content = hisArr[i].msg
				hisobj.ctime = hisArr[i].createTime
				currenID != hisArr[i].sendUserId
					? (hisobj.user = this.friendIcon)
					: (hisobj.user = this.selfIcon)
				this.nwes.push(hisobj)
			}
			console.log(this.nwes)
		},
		socket() {
			this.sock = new SockJS(
				`${
					Connect.baseURL
				}webSocketServer/?token=${localStorage.getItem(
					'userId',
				)}&type=1`,
			)
			this.stomp = Stomp.over(this.sock)
			let _this = this
			this.stomp.connect(
				{},
				function(frame) {
					//连接成功后订阅消息接口
					//订阅个人消息
					_this.stomp.subscribe('/user/queue/chat', function(
						response,
					) {
						var result = JSON.parse(response.body)
						let hisobj = {}
						hisobj.userId = 1
						hisobj.content = result.msg
						hisobj.ctime = result.createTime

						hisobj.user = _this.friendIcon

						_this.nwes.push(hisobj)
						// console.log(result)
					})
					//消息发送结果
					_this.stomp.subscribe('/user/queue/msg/result', function(
						response,
					) {})
				},
			)
		},
		test() {
			console.log('连接成功')
		},
		// 发送消息
		doSend() {
			if (this.content === '') {
				return
			}
			this._showView()
		},

		// 数据添加到数组中
		_showView() {
			let date = {
				userId: 0,
				content: this.content,
                ctime: new Date().getTime(),
                user:this.selfIcon
			}
			this.nwes.push(date)

			let sendData = JSON.stringify({
				toUserId: this.$route.params.friendId,
				msg: this.content,
				state: 0,
			})

			console.log(this.stomp)
			// 发送消息
			this.stomp.send('/ws/chat', {}, sendData)

			this.content = ''
		},
		// 判断时间是否在前台显示
		show(index) {
			if (index === 0) {
				return true
			}
			if (this.nwes[index].ctime - this.nwes[index - 1].ctime > 60000) {
				return true
			} else {
				return false
			}
		},
		// 消息推送滚动条滑动到底部
		_scrollBottom() {
			this.$nextTick(() => {
				this.$refs.input.focus()
				let scroll = this.$refs.chatContent
				scroll.scrollTop = scroll.scrollHeight
			})
		},
	},
	created() {
		this._scrollBottom()
		this.WTITLE(this.$route.params.friendName)
		this.RBACK(true)

		// 获取聊天记录
		this.getChatHis()

		// 设置个人头像
		if (this.$store.state.selfIcon) {
			this.selfIcon = this.$store.state.selfIcon
		}
		if (this.$store.state.friendIcon) {
			this.friendIcon = this.$store.state.friendIcon
		}
	},
	mounted() {
		// 与Socket建立连接
		this.socket()
	},
	watch: {
		nwes() {
			this._scrollBottom()
			return this.nwes
		},
	},
	filters: {
		formatDate(time) {
			let date = new Date(time)
			return formatDate(date, 'yyyy/MM/dd hh:mm:ss')
		},
	},
	destroyed() {
		this.sock.close()
		this.sock = {}
	},
}
</script>